package main

import (
	"autoPage/controllers"
	_ "autoPage/routers"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"github.com/wxnacy/wgo/arrays"
	"html/template"
	"runtime"
	"strconv"
	"strings"
	"time"

	"github.com/astaxie/beego/context"
	_ "github.com/go-sql-driver/mysql"
)

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	beego.SetLevel(beego.LevelInformational)
	//beego.SetLevel(beego.LevelWarning)
	beego.SetLogFuncCall(true)

	beego.BConfig.RecoverPanic = true
	beego.BConfig.RecoverFunc = RecoverPanic
	beego.SetLogger("file", `{"filename":"./logs/autopage.log"}`)
	beego.AddFuncMap("SafeUrl", SafeUrl)
	beego.AddFuncMap("IndexOf", IndexOf)
	beego.AddFuncMap("IsEq", IsEq)
	beego.AddFuncMap("IndexOfInt", IndexOfInt)
	beego.AddFuncMap("StringArrIndexOfStr", StringArrIndexOfStr)
	beego.AddFuncMap("IsOdd", IsOdd)
	beego.AddFuncMap("Contains", Contains)
	beego.AddFuncMap("Multi", Multi)
	beego.AddFuncMap("Add", Add)
	beego.Run()
}
func IsEq(s *string, ss string) bool {
	return *s == ss
}
func SafeUrl(url string) template.URL {
	safeUrl := template.URL(url)
	return safeUrl
}
func IndexOf(s, ss string) int {
	return strings.Index(s, ss)
}
func Contains(s, ss string) bool {
	return strings.Index(s, ss) >= 0
}
func Multi(args ...int) (res int) {
	res = 1
	for _, arg := range args {
		res *= arg
	}
	return
}
func Add(args ...int) (res int) {
	for _, arg := range args {
		res += arg
	}
	return
}

//是否是奇数
func IsOdd(s int) bool {
	if s == 0 {
		return false
	}
	if s%2 == 0 {
		return false
	} else {
		return true
	}
}
func StringArrIndexOfStr(s, ss string) int {
	sarr := strings.Split(s, ",")
	return arrays.ContainsString(sarr, ss)
}
func IndexOfInt(s string, ss int64) int {
	substr := strconv.FormatInt(ss, 10)
	return strings.Index(s, substr)
}
func RecoverPanic(ctx *context.Context) {
	if err := recover(); err != nil {
		var stack []string
		logs.Critical("the request url is ", ctx.Input.URL())
		logs.Critical("Handler crashed with error", err)
		for i := 1; ; i++ {
			_, file, line, ok := runtime.Caller(i)
			if !ok {
				break
			}
			logs.Critical(fmt.Sprintf("%s:%d", file, line))
			stack = append(stack, fmt.Sprintln(fmt.Sprintf("%s:%d", file, line)))
		}
		//显示错误
		dataerr := map[string]interface{}{
			"ret":           0,
			"AppError":      fmt.Sprintf("%v", err),
			"RequestMethod": ctx.Input.Method(),
			"RequestURL":    ctx.Input.URI(),
			"RemoteAddr":    ctx.Input.IP(),
			"Stack":         stack,
			"BeegoVersion":  beego.VERSION,
			"GoVersion":     runtime.Version(),
		}
		beego.Error(dataerr)
		data:=controllers.DmsResStruct{
			Status: false,
			Msg:     fmt.Sprintf("%v", err),
			Data:   nil,
		}
		_ = ctx.Output.JSON(data, true, true)
		if ctx.Output.Status != 0 {
			ctx.ResponseWriter.WriteHeader(ctx.Output.Status)
		} else {
			ctx.ResponseWriter.WriteHeader(500)
		}
	}else{

	}
}


func init() {
	dbsrc := beego.AppConfig.String("MYSQL::dbsrc")
	host := beego.AppConfig.String("MYSQL::host")
	db := beego.AppConfig.String("MYSQL::AUTOPAGE")
	orm.RegisterDriver("mysql", orm.DRMySQL)
	orm.RegisterDataBase("default", "mysql", dbsrc+"@tcp("+host+")/"+db)
	beego.BConfig.WebConfig.Session.SessionOn = true
	beego.BConfig.WebConfig.Session.SessionGCMaxLifetime = 3600*12
	if beego.AppConfig.String("runmode") != `prod` {
		beego.SetStaticPath("/swagger", "swagger")
		orm.Debug = true
	} else if beego.AppConfig.String("runmode") == "dev" {
		//beego.BConfig.WebConfig.DirectoryIndex = true
	}

	orm.SetMaxIdleConns("default", 500)
	orm.SetMaxOpenConns("default", 1000)
	sqlDB, err := orm.GetDB("default")
	if err == nil {
		sqlDB.SetConnMaxLifetime(time.Minute * 10)
	}

}
